package cn.wolfcode.car.interceptor;

import cn.wolfcode.car.domain.Employee;
import cn.wolfcode.car.domain.Permission;
import cn.wolfcode.car.qo.JsonResult;
import cn.wolfcode.car.util.RequiredPermission;
import cn.wolfcode.car.util.UserContextUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class PermissionsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            Employee currentEmployee = UserContextUtil.getCurrentEmployee();
            //判断是否超级管理员
            if(!currentEmployee.isAdmin()){
                //判断方法是否贴权限注解
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                RequiredPermission methodAnnotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
                if(methodAnnotation != null){
                    //获取当前用户的所有权限及方法上的权限
                    List<Permission> currentPermissions = UserContextUtil.getCurrentPermissions();
                    String expression = methodAnnotation.expression();
                    //判断用户权限是否符合方法权限限制
                    if(currentPermissions != null){
                        for (Permission currentPermission : currentPermissions) {
                            if(currentPermission.getExpression().equals(expression)){
                                return true;
                            }
                        }
                    }
                    //判断请求类型
                    ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
                    if(responseBody != null){
                        JsonResult jsonResult = new JsonResult(false, "您没有该访问权限,请联系管理员");
                        response.getWriter().write(JSON.toJSONString(jsonResult));
                        return false;
                    }else{
                        response.sendRedirect("/nopermission");
                    }
                }
            }
        }
        return true;
    }
}
